<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
      layout:decorate="~{manage/layout}" lang="zh">
<head>
    <title>组织管理</title>
    <style rel="stylesheet">
        .organize-tree {
            float: left;
        }

        .organize-operator-container {
            height: 56px;
            display: flex;
            align-items: center;
            margin-top: 16px;
        }

        .organize-operator-container .btn-container {
            display: flex;
            justify-content: space-between;
        }

        .mdc-tree {
            margin-top: 16px
        }

        .data-table {
            width: calc(100% - 300px);
            margin-left: 16px;
        }

    </style>
</head>
<body>
<div layout:fragment="main-container" class="main-container">
    <div class="organize-tree">
        <h2>组织管理</h2>
        <div class="organize-operator-container">
            <div class="btn-container">
                <button class="mdc-button mdc-button--raised" id="refreshBtnOrg">
                    <span class="mdc-button__label">刷新</span>
                </button>
                <a class="mdc-button mdc-button--raised" id="addBtnOrg" data-href="/manage/organize"
                   sec:authorize="hasAnyAuthority('global:create','organize:create')">
                    <span class="mdc-button__label">添加</span>
                </a>
                <button class="mdc-button mdc-button--raised" id="editBtnOrg" disabled
                        sec:authorize="hasAnyAuthority('global:write','organize:write')">
                    <span class="mdc-button__label">编辑</span>
                </button>
                <button class="mdc-button mdc-button--raised" id="delBtnOrg" disabled
                        sec:authorize="hasAnyAuthority('global:delete','organize:delete')">
                    <span class="mdc-button__label">删除</span>
                </button>
            </div>
        </div>
        <div id="mdcTree" class="mdc-tree"></div>
    </div>
    <div id="mdc-data-table" class="mdc-data-table__container mdc-float__left data-table mdc-non-display">
        <h2 id="title">组织岗位管理</h2>
        <!--扩展搜索条件-->
        <!--        <div class="search-container-extend">-->
        <!--        </div>-->
        <div class="operator-container">
            <div class="btn-container">
                <button class="mdc-button mdc-button--raised" id="refreshBtn">
                    <span class="mdc-button__label">刷新</span>
                </button>
                <a class="mdc-button mdc-button--raised" id="addBtn" data-href="/manage/post"
                   sec:authorize="hasAnyAuthority('global:create','post:create')">
                    <span class="mdc-button__label">添加</span>
                </a>
                <button class="mdc-button mdc-button--raised" id="editBtn" disabled
                        sec:authorize="hasAnyAuthority('global:write','post:write')">
                    <span class="mdc-button__label">编辑</span>
                </button>
                <button class="mdc-button mdc-button--raised" id="delBtn" disabled
                        sec:authorize="hasAnyAuthority('global:delete','post:delete')">
                    <span class="mdc-button__label">删除</span>
                </button>
            </div>
            <div class="search-container">
                <div class="mdc-text-field text-field mdc-text-field--fullwidth mdc-text-field--no-label mdc-ripple-upgraded mdc-text-field--with-trailing-icon"
                     data-mdc-auto-init="MDCTextField">
                    <input type="text" id="criteria" class="mdc-text-field__input"
                           placeholder="请输入名称" autocomplete="off" data-enter-trigger="refreshTable">
                    <i class="material-icons mdc-text-field__icon" tabindex="0" role="button" id="searchBtn">search</i>
                    <div class="mdc-line-ripple"></div>
                </div>
            </div>
        </div>
    </div>
    <!-- 添加/编辑 组织 -->
    <div th:fragment="editContainerOrg" id="editContainerOrg"></div>
    <!-- 添加/编辑 岗位 -->
    <div th:fragment="editContainer" id="editContainer"></div>
</div>
<th:block layout:fragment="script">
    <script type="text/javascript" th:inline="javascript">
      $(function() {
        console.log(' organizes: ', [[${organizes}]]);
        let organizeId;
        let initTable = 0;
        let mdcTree = $('#mdcTree').mdcTree({
          data: [[${organizes}]],
          id: 'id',
          parentId: 'prevId',
          label: 'name',
          icon: 'icon',
          expandAll: false,
          checkbox: false,
          toggleEvt: function(cell) {
            let selectItemId = cell.dataset.id;
            console.log(' 点击元素: ', selectItemId, organizeId);
            // 表格初始化,这里
            let $mdcDataTable = $('#mdc-data-table');
            !initTable++ ? window.mdcDataTable = $mdcDataTable.mdcDataTable({
                  url: '/manage/post/page',
                  queryParams: {'organizeId': selectItemId},
                  container: '#mdc-data-table',
                  columns: [
                    {
                      data: 'name',
                    },
                    {
                      data: 'dataAccessDesc',
                    },
                  ],
                  thead: [
                    {
                      data: '名称',
                      style: 'mdc-data-table__cell--non-numeric',
                    },
                    {
                      data: '数据权限',
                      style: 'mdc-data-table__cell--non-numeric',
                    },
                  ],
                  // 是否分页,暂不支持
                  pagination: true,
                  // 页面数据条数,暂不支持
                  pageSize: 5,
                  // 设置页面可以显示的数据条数,暂不支持
                  pageList: [5, 10, 15, 20],
                  // 首页页码
                  pageNumber: 1,
                  editable: false,
                  callback: function() {
                  },
                  noneSelect: function() {
                    $('#editBtn').prop('disabled', true);
                    $('#delBtn').prop('disabled', true);
                    $('#roleBtn').prop('disabled', true);
                    $('#menuBtn').prop('disabled', true);
                    $('#privilegeBtn').prop('disabled', true);
                  },
                  singleSelect: function() {
                    $('#editBtn').prop('disabled', false);
                    $('#delBtn').prop('disabled', false);
                    $('#roleBtn').prop('disabled', false);
                    $('#menuBtn').prop('disabled', false);
                    $('#privilegeBtn').prop('disabled', false);
                  },
                  multipleSelect: function() {
                    $('#editBtn').prop('disabled', true);
                    $('#delBtn').prop('disabled', false);
                    $('#roleBtn').prop('disabled', true);
                    $('#menuBtn').prop('disabled', true);
                    $('#privilegeBtn').prop('disabled', true);
                  },
                })
                : (organizeId === selectItemId ? function() {
                } : window.mdcDataTable.refresh(
                {'organizeId': selectItemId, criteria: $('#criteria').val()}));
            organizeId = selectItemId;
            $('#title').text($(cell).text() + '岗位管理');
            $mdcDataTable.show(0);
            // 组织树编辑/删除操作可用
            $('#editBtnOrg').prop('disabled', false);
            $('#delBtnOrg').prop('disabled', false);
          },
        });

        // 组织刷新
        $('#refreshBtnOrg').on('click', refreshOrganize);

        // 组织树刷新
        function refreshOrganize() {
          $.get('/manage/organize/page', {page: -1, size: -1}, function(res) {
            res.result === true ? mdcTree.refresh({data: res.data.content}) : $.alert(res.msg);
          });
        }

        // 组织添加
        $('#addBtnOrg').on('click', function() {
          console.log(organizeId);
          // if ($.isNegativeNum(organizeId)) {
          //   $.alert('请选择左侧组织');
          //   return false;
          // }
          $('#editContainerOrg').load(this.dataset.href + '?prevId=' + organizeId, () => editOrganize());
          return false;
        });

        // 编辑组织
        $('#editBtnOrg').on('click', function() {
          console.log(organizeId);
          if ($.isNegativeNum(organizeId)) {
            $.alert('请选择一条记录');
            return false;
          }
          $('#editContainerOrg').load('/manage/organize/' + organizeId, () => editOrganize(1));
          return false;
        });

        // 删除组织
        $('#delBtnOrg').on('click', function() {
          if ($.isNegativeNum(organizeId)) {
            $.alert('请选择一条记录');
            return false;
          }
          $.confirm('确认要删除这一条记录么 ?', function() {
            $.delete('/manage/organize/deleteBatch', {'ids': organizeId}, function(res) {
              console.log(JSON.stringify(res));
              $.alert(res.msg);
              refreshOrganize();
            }, function(res) {
              console.log(JSON.stringify(res));
              $.alert(res.msg);
            });
          });
        });

        window.refreshTable = function(delCount = 0) {
          window.mdcDataTable.refresh({'organizeId': organizeId, criteria: $('#criteria').val()}, delCount);
          $('#editBtn').prop('disabled', true);
          $('#delBtn').prop('disabled', true);
          $('#roleBtn').prop('disabled', true);
          $('#menuBtn').prop('disabled', true);
          $('#privilegeBtn').prop('disabled', true);
        };

        // 刷新,搜索
        $('#refreshBtn,#searchBtn').on('click', refreshTable);

        // 添加
        $('#addBtn').on('click', function() {
          console.log(organizeId);
          if ($.isNegativeNum(organizeId)) {
            $.alert('请选择左侧组织');
            return false;
          }
          $('#editContainer').load(this.dataset.href + '?organizeId=' + organizeId, () => edit());
          return false;
        });

        // 编辑
        $('#editBtn').on('click', function() {
          console.log(organizeId);
          if ($.isNegativeNum(organizeId)) {
            $.alert('请选择左侧组织');
            return false;
          }
          let selectItems = window.mdcDataTable.getSelectItems();
          if (selectItems.length !== 1) {
            $.alert('请选择一条记录');
            return false;
          }
          $('#editContainer').load('/manage/post/' + selectItems[0].id, () => edit(1));
          return false;
        });

        // TODO-WARN: 已知BUG: 每次弹窗初始化mdc-select组件,导致body会无限拼接下拉元素
        // TODO-WARN: 体验优化: 保存失败时,不应该关闭弹窗 [修复滞后]

        // 新增/更新
        function editOrganize(type = 0) {
          let thisNode = $('#editContainerOrg');
          let html = $(thisNode).html();
          $(thisNode).empty();
          $(thisNode).hide();
          $.modal({
            'title': (type === 0 ? '添加' : '编辑') + '组织',
            'content': html,
            'titleAlign': 'center',
            'openedCallback': function(data) {
              console.debug(' 打开回调log: ', data);
              $(data.target).initMDCTextField();
              $(data.target).initMDCSelect();
            },
          }, function(dom) {
            let $form = $(dom.target).find('#form');
            let data = {};
            $form.serializeArray().forEach(function(item) {
              data[item.name] = item.value;
            });
            let selects = $('.mdc-select input[name]');
            for (let i = 0; i < selects.length; i++) {
              let $input = $(selects[i]);
              let value = $input.val();
              let validTip = $input.attr('data-validtip');
              if ($input.prop('required') && (!value || Number(value) < 0)) {
                $.alert(validTip, function() {
                  $input.siblings('.mdc-select__selected-text').trigger('click');
                });
                return false;
              }
            }

            let textFields = document.querySelectorAll('.mdc-text-field');
            for (let i = 0; i < textFields.length; i++) {
              console.log(i, textFields[i]);
              let $input = $(new mdc.textField.MDCTextField(textFields[i]).input_);
              let value = $input.val();
              let required = Boolean($input.prop('required'));
              let minLength = $input.attr('minlength');
              let maxLength = $input.attr('maxlength');
              let validTip = $input.attr('data-validtip');
              let pattern = $input.attr('data-pattern');
              if (!$.valid(value, !required, minLength, maxLength, validTip || '参数校验失败', pattern)) {
                $input.trigger('focus');
                return false;
              }
            }
            data.prevId = $('input[name=prevId]').val();
            console.log(JSON.stringify(data));
            let id = $(dom.target).find('input[name=id]').val();
            console.log(' log: id = ', id);
            id > 0 ?
                $.put('/manage/organize/' + id, data, function(res) {
                  res.result === true ? $.alert(res.msg, refreshOrganize) : $.alert(res.msg);
                }) : $.post('/manage/organize', data, function(res) {
                  res.result === true ? $.alert(res.msg, refreshOrganize) : $.alert(res.msg);
                });
          });
        }

        // 新增/更新
        function edit(type = 0) {
          let thisNode = $('#editContainer');
          let html = $(thisNode).html();
          $(thisNode).empty();
          $(thisNode).hide();
          $.modal({
            'title': (type === 0 ? '添加' : '编辑') + '组织岗位',
            'content': html,
            'titleAlign': 'center',
            'openedCallback': function(data) {
              console.debug(' 打开回调log: ', data);
              $(data.target).initMDCTextField();
              $(data.target).initMDCSelect();
            },
          }, function(dom) {
            let $form = $(dom.target).find('#form');
            let data = {};
            $form.serializeArray().forEach(function(item) {
              data[item.name] = item.value;
            });
            let selects = $('.mdc-select input[name]');
            for (let i = 0; i < selects.length; i++) {
              let $input = $(selects[i]);
              let value = $input.val();
              let validTip = $input.attr('data-validtip');
              if ($input.prop('required') && (!value || Number(value) < 0)) {
                $.alert(validTip, function() {
                  $input.siblings('.mdc-select__selected-text').trigger('click');
                });
                return false;
              }
            }

            let textFields = document.querySelectorAll('.mdc-text-field');
            for (let i = 0; i < textFields.length; i++) {
              console.log(i, textFields[i]);
              let $input = $(new mdc.textField.MDCTextField(textFields[i]).input_);
              let value = $input.val();
              let required = Boolean($input.prop('required'));
              let minLength = $input.attr('minlength');
              let maxLength = $input.attr('maxlength');
              let validTip = $input.attr('data-validtip');
              let pattern = $input.attr('data-pattern');
              if (!$.valid(value, !required, minLength, maxLength, validTip || '参数校验失败', pattern)) {
                $input.trigger('focus');
                return false;
              }
            }
            data.organizeId = $('input[name=organizeId]').val();
            console.log(JSON.stringify(data));
            let id = $(dom.target).find('input[name=id]').val();
            console.log(' log: id = ', id);
            id > 0 ?
                $.put('/manage/post/' + id, data, function(res) {
                  res.result === true ? $.alert(res.msg, function() {
                    window.refreshTable();
                  }) : $.alert(res.msg);
                }) : $.post('/manage/post', data, function(res) {
                  res.result === true ? $.alert(res.msg, function() {
                    window.refreshTable();
                  }) : $.alert(res.msg);
                });
          });
        }

        // 删除
        $('#delBtn').on('click', function() {
          let selectItems = window.mdcDataTable.getSelectItems();
          let delCount = selectItems.length;
          if (delCount < 1) {
            $.alert('请至少选择一条记录');
            return false;
          }
          $.confirm('确认要删除这' + delCount + '条记录么 ?', function() {
            let ids = [];
            selectItems.forEach(function(item) {
              ids.push(item.id);
            });
            $.delete('/manage/post/deleteBatch', {'ids': ids.toString()}, function(res) {
              console.log(JSON.stringify(res));
              $.alert(res.msg);
              window.refreshTable(delCount);
            }, function(res) {
              console.log(JSON.stringify(res));
              $.alert(res.msg);
            });
          });
        });
      });
    </script>
</th:block>
</body>
</html>
